package com.pine.app.module.security.oauth.support.password;


import com.pine.app.module.security.core.userdetails.UserDetails;
import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.core.common.enums.GrantType;
import com.pine.app.module.security.oauth.exception.AuthenticationException;
import com.pine.app.module.security.oauth.provider.client.ClientDetails;
import com.pine.app.module.security.oauth.provider.client.ClientDetailsService;
import com.pine.app.module.security.oauth.support.AbstractPreparableIntegrationValidator;
import com.pine.app.module.security.oauth.support.HttpTokenRequest;
import com.pine.app.module.security.oauth.provider.OAuth2Authentication;
import com.pine.app.module.security.oauth.user.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;


/**
 * @author xiaoyuan
 * @create 2019/9/3 15:23
 **/

public class PasswordValidator extends AbstractPreparableIntegrationValidator {

    private LoginService loginService;


    @Autowired
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    public PasswordValidator() {

    }

    public PasswordValidator(ClientDetailsService clientDetailsService,
                             LoginService loginService) {
        super(clientDetailsService);
        this.loginService = loginService;
    }

    @Override
    public HttpTokenRequest createRequest(HttpServletRequest request) {
        return new HttpPasswordRequest(request);
    }

    @Override
    protected OAuth2Authentication checkParam(HttpTokenRequest request) {
        HttpPasswordRequest passwordRequest = (HttpPasswordRequest) request;
        if (StringUtils.isBlank(passwordRequest.getUsername())) {
            ErrorType.ILLEGAL_USERNAME_OR_PASSWORD.throwThis(AuthenticationException::new);
        }
        if (StringUtils.isBlank(passwordRequest.getPassword())) {
            ErrorType.ILLEGAL_USERNAME_OR_PASSWORD.throwThis(AuthenticationException::new);
        }
        //检查客户端其他信息
        ClientDetails clientDetails = this.checkClientInfo(request);
        //检查用户信息
        UserDetails userDetails = this.loginService.login(passwordRequest);
        return new  OAuth2Authentication(coverOauth2Request(clientDetails,request),userDetails);
    }


    @Override
    public String getGrantType() {
        return GrantType.PASSWORD.getName();
    }

}
